# coding=utf-8
import os
import shutil
import sqlite3

import pandas
from loguru import logger

from cal_ops.point import cal_point2db, cal_point2, cal_point1
from mylib import download_all
from mylib.mydb import MyDB


def clear_dir(d='result'):
    shutil.rmtree(d)
    os.makedirs(d)


def get_all_stock_csv_path():
    for root, dirs, files in os.walk('stocks'):
        return [os.path.join(root, item) for item in files]


def change_all_stockcsv2sqlite():
    all_stocks_path_list = get_all_stock_csv_path()
    for sp in all_stocks_path_list:
        table_name = sp.replace('.csv', '').replace('stocks/', 'stock_').replace('.', '_')
        mydb.change_csv2sqlite(csv_name=sp, table_name=table_name, from_col=1)


def get_stocks_indus(stocks):
    indus_set = set()
    for stock in stocks:
        indus_set.add(mydb.select_indus_from_db(stock))
    indus = list(indus_set)
    return indus


if __name__ == '__main__':
    mydb = MyDB()

    # change all to sqlite
    # table_name = 'stocks'
    # mydb.change_csv2sqlite(csv_name='all.csv', table_name='stocks')
    # mydb.change_csv2sqlite(csv_name='industry_count_rank.csv', table_name='industry_count_rank')
    # change_all_stockcsv2sqlite()
    # logger.add("{time}.log", level='INFO')
    # clear_dir()
    # bkd = 210
    # start_date = 20230505
    bkd = 5
    start_date = 20241212
    stocks = [
        '000001.SZ',
        # '000151.SZ',
        '600438.SH',
        # '600482.SH',
        # '600699.SH',
        # '601012.SH',
        # '603003.SH',
        # '603109.SH',
    ]
    indus = get_stocks_indus(stocks)
    # print(indus)
    # indus = [
    #     '电气设备',
    #     '商贸代理',
    #     '汽车配件',
    #     '船舶',
    #     '银行',
    #     '石油贸易'
    # ]

    # res = mydb.select_all_indus_from_db()
    # print(len(list(set(res))))
    # stocks = None

    # 更新所有上市票
    # update_all_csv.run()
    # 下载所有票最新数据
    download_all.run(stocks)

    # 计算最近40个峰谷点
    log_dir = os.path.basename(__file__).split('.')[0]
    cal_point1.run(log_dir, start_date, stocks, indus=indus, bkd=bkd, N=6)
    # main_name_for2.run(stocks, indus=indus, bkd=bkd, N=6)
    # cal_point2db.run(stocks, indus=indus, bkd=bkd, N=6)

    # todo 计算下跌超过平均的个数

    # 分析单支股票，配置在 ana_config.txt
    # ana_one.run(stocks, ana_days=100)

    # 上次连涨距离计算
    # cal_day_up_times.run(stocks=stocks, bkd=bkd)

    # 上次连跌距离计算
    # cal_day_down_times.run(stocks=stocks, bkd=bkd)

    # 计算排名
    # cal_rank2.run(stocks, bkd=bkd, N=6)

    # 计算步步高
    # top_10_eq3.run(stocks, bkd=bkd, N=5)
